import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Role } from '../entities/role.entity';

@Injectable()
export class AuthService {
    constructor(
        private readonly jwtService: JwtService,
        @InjectRepository(Role)
        private roleRepository: Repository<Role>,
    ) {}

    async login(loginDto: { username: string; password: string; permission: string }) {
        // 查找用户
        const user = await this.roleRepository.findOne({
            where: {
                username: loginDto.username,
                permission: loginDto.permission
            }
        });

        if (!user) {
            throw new UnauthorizedException('用户名或权限不正确');
        }

        // 这里应该添加密码验证
        if (user.password !== loginDto.password) {
            throw new UnauthorizedException('密码不正确');
        }

        const payload = { 
            username: user.username, 
            permission: user.permission,
            userId: user.id 
        };

        return {
            token: this.jwtService.sign(payload),
            userId: user.id,
            username: user.username
        };
    }
} 